
import javanetworking.Squery;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javanetworking.host;
import sun.awt.image.BufImgSurfaceData;

/**
 *
 * @author NGUYEN
 */
public class Peertopeer {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws SocketException, IOException, Exception {
        // TODO code application logic here
        List<host> lstHost = new ArrayList<>();
        DatagramSocket socket = new DatagramSocket(1235);
        File fi_nodes = new File("nodes.map");
        BufferedReader br = new BufferedReader(new FileReader(fi_nodes));
        int nhost = Integer.parseInt(br.readLine());
        for (int i = 0; i < nhost; i++) {
            String[] s = br.readLine().split(" ");
            host h = new host();
            h.setId(Integer.parseInt(s[0]));
            h.setIp(s[1]);
            h.setPort(Integer.parseInt(s[2]));
            lstHost.add(h);
        }
        for (int i = 0; i < lstHost.size(); i++) {
            Squery squery = new Squery();
            squery.setCode(0);
            squery.setFilename("File 1");
            squery.setOffset(0);
            squery.setiChunk(1);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream ois = new ObjectOutputStream(baos);
            ois.writeObject(squery);
            host e = lstHost.get(i);


            new Thread(new javanetworking.Send(socket, e.getIp(), e.getPort(), baos.toByteArray())).start();

        }
        DatagramPacket pk = new DatagramPacket(new byte[100], 100);
        pk.setAddress(InetAddress.getByName("192.168.9.103"));
        pk.setPort(1234);
        //new Thread(new Respone(socket,pk)).start();
        new Thread(new Requests(socket)).start();
    }
}

class Respone implements Runnable {

    DatagramSocket socket;
    DatagramPacket packet;

    Respone(DatagramSocket csocket) {
        this.socket = csocket;
    }

    Respone(DatagramPacket cpacket) {
        this.packet = cpacket;
    }

    Respone(DatagramSocket csocket, DatagramPacket cpacket) {
        this.packet = cpacket;
        this.socket = csocket;
    }

    @Override
    public void run() {
        try {
            byte[] sendbuf = new byte[1024];
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                System.out.print("Server: ");
                InetAddress add = InetAddress.getByName(this.packet.getAddress().getHostName());
                String stSend;
                stSend = in.readLine();
                sendbuf = stSend.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(sendbuf, sendbuf.length, add, this.packet.getPort());
                this.socket.send(sendPacket);
            }
        } catch (SocketException ex) {
            Logger.getLogger(Respone.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Respone.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

class Requests implements Runnable {

    DatagramSocket socket;

    Requests(DatagramSocket csocket) {
        this.socket = csocket;
    }

    @Override
    public void run() {
        try {
            while (true) {
                byte[] rcvbuf = new byte[512];
                String stRcv;
                DatagramPacket rcvpkt = new DatagramPacket(rcvbuf, rcvbuf.length);
                socket.receive(rcvpkt);
                ByteArrayInputStream bis = new ByteArrayInputStream(rcvpkt.getData());
                ObjectInputStream ois = new ObjectInputStream(bis);
                Squery q = (Squery) ois.readObject();
                if (q.getCode() == 2) {
                    q.setCode(1);
                    try {
                        new Thread(new javanetworking.Send(socket, rcvpkt.getAddress().getHostAddress(), rcvpkt.getPort(), q.toByteArray())).start();
                    } catch (Exception ex) {
                        Logger.getLogger(Requests.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

            }
        } catch (SocketException ex) {
            Logger.getLogger(Requests.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Requests.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Requests.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
